package cn.tedu.tmall.front.mall.alipay.controller;

import cn.tedu.tmall.front.mall.alipay.pojo.param.PayParam;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理在线支付相关请求的控制器类
 *
 * @author java@tedu.cn
 * @version 3.0
 */
@Slf4j
@Api(tags = "9. 模拟支付")
@RestController
@RequestMapping("/alipay")
public class PayController {

    /**
     * APP ID，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String APP_ID = "9021000138695167";
    /**
     * 应用私钥，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZqs6qhjoBwZyM8EfX8RyJ1dLfqjzdlFN3juTzOenJlkMqg/4m3VmZVh9850EYa4Y7pQ/fQoIGg42L/X9UkMX0FWUrq2CUQrlfzHQWUABrdkvuWIQL9gb0e68vbel9g/We4Jc2bdbuvOPiAYuWyMPyz5lP9qOpDkZ6cO/nGzFm7KAqj8CvwovHR+Si0PSmlSvWuSJa8sUGqmnv6AUyKo7+OmRgA6IFHLkwX7R5165vLi8xCz+qGOgDBVeYvedpb4mWnP9AzyKgdq4VvuC5TI9pmruDwecCZA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iVNxAqOMa77cCvFaioLe9bqITYl87QgNAoGAHfV5QSsCli26yb9SOGawKg0j+XCH+OwVLN5cM/Nl2D4gotY6I9WSvbXqUak7Z+4IYyNukcjFbSiRpodcTU+XpduQbsOBd1i+D8k7J1EPBj+d+Vv4UCVw96Dg7kfZ4JmL44N9CUvlhZDLqoiYdA4iC5sjOJW63ZPf2GLCMyg4//g=";
    /**
     * 支付宝公钥，请在支付宝沙箱应用（https://open.alipay.com/develop/sandbox/app）中查找正确的值
     */
    private static final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkn0t0k5iLl1d18qP+Xqw1h8CW5fnCgXkgBr1h349C/jsf3nKdrqTpg2YDI5sRlkbiOMEkDddrbRlZxTTjz62ljlwST8QZK2bY6BBbSTNvIADqs6IcG/a5BqjjtI9Xz9sfXFnabWJ/LKtQ5IsQGrngLa6hFneHcytFYsfXZKIHxp6lpBjwydEZJi8N7fbqHQ8UMB1iCgSlLa0hZwgiXuNuWl3lCH3aBRR2TlitqfQccCgwWcOlAVuRuzKVxcyolVD0/ezOeDGLI1+oFw5wV3R+vizMzT7DhmwbveM3EV/oRZ5Bh9cmcESk84LvtHZjEHcJAD//1JefxXnPE6dseMUfQIDAQAB\n";
    /**
     * 支付服务器的主机，请参考你的服务器配置，或内网穿透的端口映射配置
     */
    private static final String PAY_HOST = "http://2239vh.natappfree.cc ";
    /**
     * 通知网址，用于处理支付宝完成支付处理后，你的应用中进行下一步处理的请求地址，请参考当前控制器的配置
     */
    private static final String NOTIFY_URL = PAY_HOST + "/alipay/notify";
    /**
     * 返回网址，用于支付宝完成支付处理后，重定向到某个位置，请参考当前控制器的配置
     */
    private static final String RETURN_URL = PAY_HOST + "/alipay/finish";
    /**
     * 【固定】支付宝网关
     */
    private static final String ALIPAY_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    /**
     * 【固定】加密算法
     */
    private static final String ENCRYPTION_ALGORITHM = "RSA2";
    /**
     * 【固定】字符编码
     */
    private static final String CHARSET = "UTF-8";
    /**
     * 【固定】数据格式
     */
    private static final String DATA_FORMAT = "json";

    public PayController() {
        log.debug("创建控制器类对象：PayController");
    }

    // 此方法用于接收客户端发起的支付请求，并响应支付表单页面到客户端
    // 网页客户端应该通过window.open直接向此处发起请求，则响应的支付表单会直接显示在window.open打开的窗口中
    @ApiOperation("支付宝沙箱支付")
    @ApiOperationSupport(order = 100)
    @GetMapping("/pay")
    public String pay(PayParam payParam, @ApiIgnore HttpServletResponse response) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(
                ALIPAY_GATEWAY, APP_ID, PRIVATE_KEY, DATA_FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, ENCRYPTION_ALGORITHM);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(NOTIFY_URL);
        //同步跳转地址，仅支持http/https
        request.setReturnUrl(RETURN_URL);
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", payParam.getOutTradeNo());
        //支付金额，最小值0.01元
        bizContent.put("total_amount", payParam.getTotalAmount());
        //订单标题，不可使用特殊符号
        bizContent.put("subject", payParam.getSubject());
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        /******可选参数******/
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse alipayTradePagePayResponse = alipayClient.pageExecute(request);
        if (alipayTradePagePayResponse.isSuccess()) {
            System.out.println("调用成功，将在浏览器中打开支付宝【沙箱】支付页");
            String responseBody = alipayTradePagePayResponse.getBody();
            System.out.println(responseBody);
            return responseBody;
        } else {
            return "交易失败，调用支付宝远程接口失败，请返回订单页查看订单状态，或重新支付！";
        }
    }

    // 接收支付宝发送的通知（支付结果）
    // 注意：必须是POST请求
    @ApiIgnore
    @PostMapping("/notify")
    public String payNotify(@ApiIgnore HttpServletRequest request) throws Throwable {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, ALIPAY_PUBLIC_KEY, CHARSET); // 验证签名
        // 支付宝验签
        if (checkSignature) {
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家支付宝ID: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
            // 你应该在此处补充支付成功后续的代码，例如修改订单状态等
            // 完成
            return "支付完成，商家将尽快发货";
        } else {
            return "支付失败，请返回订单页查看订单状态，或重新支付！";
        }
    }

    // 接收处理支付宝的跳转（支付完成后自动重定向到此处）
    @ApiIgnore
    @GetMapping("/finish")
    public String finish() {
        return "支付完成，请返回订单页查看订单状态！";
    }

}
